package com.kindnesslibrary.base;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import com.kindnesslibrary.util.ToastUtil;

import java.util.concurrent.ExecutorService;

public abstract class BaseDialog extends Dialog implements View.OnClickListener {

    protected ExecutorService executorService; // 线程池

    /**
     * 布局id
     */
    private int reId;

    /**
     * 不改变属性
     */
    public static final int UN_CHANGED = -10;

    /**
     * 数据相关
     */
    private int width = UN_CHANGED;// dialog宽度
    private int height = UN_CHANGED;// dialog高度

    protected View view;

    public BaseDialog(Context context) {
        super(context);
    }

    protected BaseDialog(Context context, boolean cancelable,
                         OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public BaseDialog(Context context, int theme) {
        super(context, theme);
    }

    public BaseDialog(Context context, int theme, int width, int height) {
        super(context, theme);
        this.width = width;
        this.height = height;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.reId = init();
        view = LayoutInflater.from(getContext()).inflate(reId, null);
        setContentView(view);
        initView(view);
        setViewData();
        initEvent();
    }

    /**
     * 初始化
     *
     * @return 布局
     */
    protected abstract int init();

    /**
     * 初始化控件
     */
    protected abstract void initView(View view);

    /**
     * 初始化控件属性
     */
    protected abstract void setViewData();

    /**
     * 初始化控件事件
     */
    protected abstract void initEvent();

    /**
     * 获取数据
     */
    protected abstract void getData();

    @Override
    public void show() {
        super.show();
        if (width != UN_CHANGED || height != UN_CHANGED) {
            WindowManager.LayoutParams wlp = getWindow().getAttributes();
            if (width != UN_CHANGED)
                wlp.width = width;
            if (height != UN_CHANGED)
                wlp.height = height;
            getWindow().setAttributes(wlp);
        }
    }

    public String getString(int strId) {
        return getContext().getString(strId);
    }

    protected void startRunnable(Runnable runnable) {
        if (runnable == null) {
            ToastUtil.showToast("Send failed.");
            return;
        }
        if (executorService == null) {
            executorService = BaseApplication.getInstance().getExecutorService();
        }
        executorService.execute(runnable);
    }

}
